package com.mustafaiev.tair.autobase.web.command;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mustafaiev.tair.autobase.dao.OrderDao;
import com.mustafaiev.tair.autobase.dao.OrderDaoImpl;
import com.mustafaiev.tair.autobase.order.ClientOrder;

/**
 * 
 * The Command class implements {@link AutobaseServletCommand} and provides
 * creation of client order
 * 
 * @author Tair Mustafaiev
 *
 */
public class OrderCommandImpl implements AutobaseServletCommand {

    private static final Logger LOG = Logger.getLogger(OrderCommandImpl.class.getName());

    @Override
    public void processGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

    }

    @Override
    public void processPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        
        OrderDao dao = new OrderDaoImpl();
        
        ClientOrder order = new ClientOrder();
        if (req.getParameter("name") != null) {
            order.setName(req.getParameter("name"));
        }
        if (req.getParameter("phone") != null) {
            order.setPhone(req.getParameter("phone"));
        }
        if (req.getParameter("propose") != null) {
            order.setOrder(req.getParameter("propose"));
        }
        if (req.getParameter("create_date") != null) {
            order.setCreateDate(Long.valueOf(req.getParameter("create_date")));
        }

        try {
            dao.createOrder(order);
            LOG.info("Added new order: " + " Client name: " + req.getParameter("name")
                    + ", Client phone: " + req.getParameter("phone") + ", Conditions: "
                    + req.getParameter("propose") + ", Date: " + Calendar.getInstance().getTime());
        } catch (SQLException e) {
            LOG.error(e);

        }
        req.getSession(true).setAttribute("message", "Your order was successful sent!");
        resp.sendRedirect("/index.jsp");
    }

}
